<?php
/* 
 * Copyright (c) 2011 Antoine d'Otreppe de Bouvette
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

class Dispatcher {
    /**
     * @var Environment
     */
    private $env;
    
    /**
     * @var Controller
     */
    private $defaultController;
    
    /**
     * @var array
     */
    private $routes = array();
    
    /**
     *
     * @param Environment $env
     * @param array $routes
     * @param array $mapping
     */
    public function __construct(Environment $env,
                                array $routes, array $mapping) {
        $this->env = $env;
        
        foreach ($routes as $name=>$pattern) {
            $regex = '#^' . preg_replace_callback(
                    AspyctURL::URL_PARAM_PATTERN,
                function ($match) {
                    $name = $match['name'];
                    if (array_key_exists('regex', $match)) {
                        $regex = $match['regex'];
                    }
                    else {
                        $regex = '[^/]+';
                    }

                    return "(?P<$name>$regex)";
                },
                $pattern) . '$#';

            if (array_key_exists($name, $mapping)) {
                $controller = explode('.', $mapping[$name], 2);
            }
            else {
                $parts = explode('.', $name, 2);
                
                if (count($parts) === 1) {
                    $controller = array($name);
                }
                else {
                    $controller = $parts;
                }
            }
            
            $this->routes[$regex] = $controller;
        }
    }
    
    /**
     * @param Request $request
     * @return Handler
     */
    public function findController(Request $request) {
        $uri = $request->getUri();
        
        foreach ($this->routes as $pattern=>$controller) {
            if (preg_match($pattern, $uri, $match)) {
                $request->setArguments($match);
                
                if (count($controller) === 1) {
                    return new StandardHandler(
                            $this->getController($controller[0]));
                }
                else {
                    return new SpecificMethodHandler(
                            $this->getController($controller[0]),
                            $controller[1]);
                }
            }
        }
        
        return new StandardHandler($this->env->defaultController);
    }
    
    private function getController($name) {
        if (isset($this->env->$name)) {
            $name = 'default';
        }
        
        return $this->env->{$name.'Controller'};
    }
}
